package com.mall.service.Impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.mall.entity.SmoothMallCategory;
import com.mall.entity.dto.SmoothMallCategoryDto;
import com.mall.entity.dto.TreeDto;
import com.mall.mapper.SmoothMallCategoryMapper;
import com.mall.service.SmoothMallCategoryService;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

@Service
public class SmoothMallCategoryServiceImpl extends ServiceImpl<SmoothMallCategoryMapper, SmoothMallCategory> implements SmoothMallCategoryService {
    @Override
    public List<SmoothMallCategoryDto> listDto(Integer id) {
        List<SmoothMallCategory> list_ = list();
        List<SmoothMallCategoryDto> list=new ArrayList<SmoothMallCategoryDto>();
        //将查询结果封装为dto
        list_.stream().forEach(i->{
            SmoothMallCategoryDto smoothMallCategoryDto = new SmoothMallCategoryDto();
            BeanUtils.copyProperties(i,smoothMallCategoryDto);
            list.add(smoothMallCategoryDto);
        });
        Map<Integer, SmoothMallCategoryDto> treeMap = list.stream()
                .filter(key -> !key.getId().equals(id))
                .collect(Collectors.toMap(key -> key.getId(), value -> value));
        List<SmoothMallCategoryDto> smoothMallCategoryDtosResult=new ArrayList<SmoothMallCategoryDto>();
        list.stream().forEach(item->{
            if (item.getParentId().equals(id)){
                smoothMallCategoryDtosResult.add(item);
            }else {
                SmoothMallCategoryDto parentCategoryDto = treeMap.get(item.getParentId());
                if (parentCategoryDto!=null){
                    if (parentCategoryDto.getChildCategory()==null){
                        parentCategoryDto.setChildCategory(new ArrayList<SmoothMallCategoryDto>());
                    }
                    parentCategoryDto.getChildCategory().add(item);
                }
            }
        });
        return smoothMallCategoryDtosResult;
    }

}
